/**
 * @file 应用入口文件
 * @description 应用初始化、全局配置和Vue实例创建
 * @date 2024-08-14 (更新)
 */
import { createSSRApp } from 'vue'
import App from './App.vue'
import './styles/index.scss'
import { createAppPinia } from './stores'
import { appInitializer, registerCoreInitTasks, InitLevel, InitPriority } from './services/appInitializer'
import { logger } from '@/utils/system/logger'
import { useMapStore } from '@/stores/modules/map'

/**
 * 注册错误处理任务
 */
function registerErrorHandlingTasks(): void {
  // 全局未捕获的Promise错误处理
  if (typeof window !== 'undefined') {
    window.addEventListener('unhandledrejection', event => {
      logger.error('未捕获的Promise错误:', event.reason);
    });
    
    // 开发环境检测API可用性
    if (process.env.NODE_ENV === 'development') {
      window.addEventListener('DOMContentLoaded', () => {
        const mapStore = useMapStore()
        logger.debug('初始地图能力:', mapStore.capabilities)
      });
    }
  }

  // 注册全局错误处理任务
  appInitializer.registerTask({
    name: 'core:error-handling',
    level: InitLevel.CORE,
    priority: InitPriority.HIGH,
    handler: async () => {
      logger.info('初始化全局错误处理...');
      return Promise.resolve();
    },
    description: '初始化全局错误处理'
  });
}

// 创建应用
export function createApp() {
  // 创建应用实例
  const app = createSSRApp(App)
  
  logger.info('创建应用实例')
  
  // 初始化Pinia状态管理
  const pinia = createAppPinia()
  app.use(pinia)
  
  // 注册初始化任务
  registerCoreInitTasks()
  
  // 注册uni-app路由初始化任务
  appInitializer.registerTask({
    name: 'core:uni-app-route',
    level: InitLevel.CORE,
    priority: InitPriority.HIGH,
    handler: async () => {
      logger.info('初始化uni-app路由...');
      return Promise.resolve();
    },
    description: '初始化uni-app路由'
  });
  
  // 注册错误处理任务
  registerErrorHandlingTasks()
  
  // 全局错误处理
  app.config.errorHandler = (err: unknown, vm: any, info: string) => {
    logger.error('应用错误:', err, vm?.$options?.name || 'unknown', info);
  }

  // 全局警告处理
  app.config.warnHandler = (msg: string, instance: any, trace: string) => {
    logger.warn('应用警告', {
      message: msg,
      component: instance?.$options?.name || 'unknown',
      trace
    });
  }
  
  // 开发环境日志
  if (process.env.NODE_ENV === 'development') {
    logger.info('应用启动', { 
      env: process.env.NODE_ENV,
      version: import.meta.env.VITE_APP_VERSION
    });
  }

  // 启动统一初始化流程
  queueMicrotask(() => {
    appInitializer.initialize()
      .then(() => logger.info('统一初始化完成'))
      .catch(error => logger.error('初始化过程出错:', error));
  });

  logger.info('应用初始化完成')
  
  return { app }
}

// 创建应用
const { app } = createApp()

// 挂载应用
app.mount('#app')

logger.info('GPS轨迹可视化系统已启动') 